package com.zhende.hr.interceptor;

import java.io.IOException;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import com.alibaba.fastjson.JSON;
import com.zhende.hr.utils.JwtTokenProvider;
import com.zhende.hr.utils.R;

@Component
public class JWTFilter extends OncePerRequestFilter {

    @Autowired
    private JwtTokenProvider jwtTokenProvider;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {
    	
        // 从请求头中获取 JWT Token
        String token = request.getHeader("Authorization");
        if (token != null && token.startsWith("Bearer ")) {
            token = token.substring(7);  // 去掉 "Bearer " 前缀

            // 验证 token 并获取用户信息
            if (jwtTokenProvider.validateToken(token)) {
                Authentication authentication = jwtTokenProvider.getAuthentication(token);
                SecurityContextHolder.getContext().setAuthentication(authentication);
            }else {
                throw new AccessDeniedException("Token 已失效或无效，请重新登录");

//                response.setContentType("application/json;charset=UTF-8");  // 设置响应类型为 JSON，并指定编码为 UTF-8
//                R r = R.error("Token 已失效或无效，请重新登录");
//                response.getWriter().write(JSON.toJSONString(r));  // 返回自定义的错误消息
//                return;  // 不再继续执行过滤器链
            }
        }
        //  throw new AccessDeniedException("Token 已失效或无效，请重新登录");

        filterChain.doFilter(request, response);  // 继续执行过滤器链
    }
}
